package cn.eric.framework.utils.dao.i;

import cn.eric.framework.ajax.EricContext;
import cn.eric.framework.ajax.EricContextInnerResponse;
import cn.eric.framework.utils.dao.GeneralDao;
import org.hibernate.query.Query;
import org.springframework.orm.hibernate5.HibernateTemplate;

import javax.annotation.Resource;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

//@Component
public class IGeneralDao<T> implements GeneralDao<T> {
    private final static String HQL_PAGING_RESULT_TEMPLATE = "FROM %s";
    private final static String HQL_PAGING_TOTAL_PAGE_TEMPLATE = "SELECT COUNT(*) FROM %s";
    @Resource
    private HibernateTemplate hibernateTemplate;

    private Class<T> entityClass;

    public IGeneralDao() {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        entityClass = (Class) params[0];
    }

    @Override
    public void save(T t) {
        hibernateTemplate.save(t);
    }

    @Override
    public T get(Serializable id) {

        return hibernateTemplate.get(entityClass, id);
    }

    @Override
    public EricContextInnerResponse<T> getWithPaging(EricContext context) {
        context.setTotalPage(hibernateTemplate.execute(session -> {
            Query query = session.createQuery(String.format(HQL_PAGING_TOTAL_PAGE_TEMPLATE, entityClass.getSimpleName()));
            return (int) query.list().get(0);
        }));
        return new EricContextInnerResponse<>(hibernateTemplate.execute(session -> {
            Query query = session.createQuery(String.format(HQL_PAGING_RESULT_TEMPLATE, entityClass.getSimpleName()));
            query.setFirstResult(context.getCurrentPage() * context.getRowPerPage());
            query.setMaxResults(context.getRowPerPage());
            return query.list();
        }), context);
    }
}
